<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="所属项目" prop="projectId">
        <el-select v-model="queryParams.projectId"
                   placeholder="请选择所属项目"
                   clearable
                   @keyup.enter.native="handleQuery" @change="projectChange">
          <el-option
            v-for="dict in projectOptions"
            :key="dict.projectId"
            :label="dict.projectName"
            :value="dict.projectId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属设备" prop="deviceId">
        <treeselect
          v-model="queryParams.deviceId"
          :options="deviceList"
          :normalizer="normalizer"
          :show-count="true"
          clearable
          style="width:215px;"
          placeholder="选择所属设备"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="传感器编号" prop="sensorCode">
        <el-input
          v-model="queryParams.sensorCode"
          placeholder="请输入传感器编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="传感器名字" prop="sensorName">
        <el-input
          v-model="queryParams.sensorName"
          placeholder="请输入传感器名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计量单位" prop="unit">
        <el-select
          v-model="queryParams.unit"
          clearable
          filterable
          placeholder="请选择计量单位"
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="dict in dict.type.app_sensor_unit"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['app:sensor:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['app:sensor:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['app:sensor:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleUpload"
          v-hasPermi="['app:sensor:edit']"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['app:sensor:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      style="margin: 30px 0px"
    />
    <el-table v-loading="loading" :data="sensorList" @selection-change="handleSelectionChange">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand" label-width="150px">
            <el-form-item label="所属设备">
              <span>{{ props.row.deviceName ? props.row.deviceName : '' }}</span>
            </el-form-item>
            <el-form-item label="传感器名字">
              <span>{{ props.row.sensorName }}</span>
            </el-form-item>
            <el-form-item label="传感器编号">
              <span>{{ props.row.sensorCode }}</span>
            </el-form-item>
            <el-form-item label="告警类型">
              <span>{{ props.row.ruleName ? props.row.ruleName : '' }}</span>
            </el-form-item>
            <el-form-item v-if="props.row.gatewayName && props.row.gatewayName" label="网关">
              <span>{{ props.row.gatewayName }}</span>
            </el-form-item>
            <el-form-item
              v-if="props.row.gatewayType && props.row.gatewayType === '1'"
              label="PLC设备">
              <span>{{
                  props.row.gatewayName ? props.row.gatewayName : ''
                }}</span>
            </el-form-item>
            <el-form-item
              v-if="props.row.gatewayType && props.row.gatewayType === '1'"
              label="读取地址">
              <span>{{ props.row.outputAddress }}</span>
            </el-form-item>
            <el-form-item
              v-if="props.row.gatewayType && props.row.gatewayType === '2'"
              label="MQTT的订阅主题">
              <span>{{ props.row.mqttTopic }}</span>
            </el-form-item>
            <el-form-item
              v-if="props.row.gatewayType && props.row.gatewayType === '2'"
              label="MQTT写入主题">
              <span>{{ props.row.mqttWriteTopic }}</span>
            </el-form-item>
            <el-form-item
              v-if="props.row.gatewayType && props.row.gatewayType === '2'"
              label="MQTT的通道号">
              <span>{{ props.row.mqttDeviceChannel }}</span>
            </el-form-item>
            <el-form-item
              v-if="props.row.gatewayType && props.row.gatewayType === '2'"
              label="MQTT的设备名称">
              <span>{{ props.row.mqttDeviceName }}</span>
            </el-form-item>
            <el-form-item
              v-if=" props.row.gatewayType && props.row.gatewayType === '2'"
              label="MQTT的标记">
              <span>{{ props.row.mqttDeviceTag }}</span>
            </el-form-item>
            <el-form-item label="当前数值">
              <span v-if="props.row.valueDesc">{{ props.row.valueDesc }}</span>
              <span v-else-if="props.row.unit.indexOf('开关量') > -1 ">{{
                  props.row.value ? props.row.value === '1' ? '开' : '关' : ''
                }}</span>
              <span v-else>
                {{ props.row.value + props.row.unit }}
              </span>
            </el-form-item>
            <el-form-item label="三维编号">
              <span>{{ props.row.tdCode }}</span>
            </el-form-item>
            <el-form-item label="传感器类型">
              <span>{{ dict.label.app_sensor_type[props.row.sensorType] }}</span>
            </el-form-item>
            <el-form-item label="放大倍数">
              <span>{{ props.row.magnification }}倍</span>
            </el-form-item>
            <el-form-item label="取值周期">
              <span>{{ props.row.intervalTime }}毫秒</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="ID" align="center" prop="sensorId"/>
      <el-table-column prop="deviceName" label="所属设备"/>
      <!--      <el-table-column label="网关类型" align="center" prop="device.appGateway">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{-->
      <!--             scope.row.device-->
      <!--             && scope.row.device.appGateway-->
      <!--             && scope.row.device.appGateway.gatewayType-->
      <!--             && scope.row.device.appGateway.gatewayType === '1' ? "PLC" :-->
      <!--               scope.row.device-->
      <!--               && scope.row.device.appGateway-->
      <!--               && scope.row.device.appGateway.gatewayType-->
      <!--               && scope.row.device.appGateway.gatewayType === '2' ? "MQTT" : '其他网关'-->
      <!--            }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="网关名称" align="center" prop="device.appGateway">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{-->
      <!--              scope.row.device &&   scope.row.device.appGateway && scope.row.device.appGateway.gatewayType ? scope.row.device.appGateway.gatewayName : ''-->
      <!--            }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="传感器编号" align="center" prop="sensorCode"/>
      <el-table-column label="传感器名字" align="center" prop="sensorName"/>
      <el-table-column label="传感器类型" align="center" prop="sensorType">
        <template slot-scope="scope">
          {{ dict.label.app_sensor_type[scope.row.sensorType + ""] }}
        </template>
      </el-table-column>
      <el-table-column prop="value" label="当前数值">
        <template slot-scope="scope">
          <span v-if="scope.row.valueDesc">{{ scope.row.valueDesc }}</span>
          <span v-else-if="scope.row.unit.indexOf('开关量') > -1" >{{
              scope.row.value ? scope.row.value === '1' ? '开' : '关' : ''
            }}</span>
          <span v-else>
                {{ (scope.row.value ? scope.row.value : '') + scope.row.unit }}
              </span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="150px">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['app:sensor:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['app:sensor:remove']"
          >删除
          </el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleDeptScope" icon="el-icon-circle-check"
                                v-hasPermi="['app:sensor:edit']">所属部门
              </el-dropdown-item>
              <el-dropdown-item command="handlePlaceScope" icon="el-icon-circle-check"
                                v-hasPermi="['app:sensor:edit']">空间位置
              </el-dropdown-item>
              <el-dropdown-item command="handleOpenRecord" icon="el-icon-circle-check">数值记录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改传感器管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body :close-on-click-modal="false">
      <el-form v-show="!isUpload" ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属设备" prop="deviceId">
              <treeselect
                v-model="form.deviceId"
                :options="deviceList"
                :normalizer="normalizer"
                :show-count="true"
                clearable
                style="width: 100%;"
                placeholder="选择所属设备"
                @select="deviceSelect"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="告警规则" prop="faultRuleId">
              <el-select v-model="form.faultRuleId" placeholder="请选告警规则">
                <el-option
                  v-for="item in faultRuleList"
                  :key="item.faultRuleId"
                  :label="item.ruleName"
                  :value="item.faultRuleId"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="传感器名字" prop="sensorName">
              <el-input v-model="form.sensorName" placeholder="请输入传感器名字" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="传感器编号" prop="sensorCode">
              <el-input v-model="form.sensorCode" placeholder="请输入传感器编号" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="三维编号" prop="tdCode">
              <el-input v-model="form.tdCode" placeholder="请输入三位编码" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="传感器类型" prop="sensorType">
              <el-select
                v-model="form.sensorType"
                clearable
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="dict in dict.type.app_sensor_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="取值周期" prop="intervalTime">
              <el-input v-model="form.intervalTime" placeholder="请输入取值周期" clearable/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="传感器值" prop="value">
              <el-input v-model="form.value" placeholder="请输入传感器值" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">

            <el-form-item label="取值周期" prop="intervalTime">
              <el-input-number
                v-model="form.intervalTime"
                :precision="0"
                :step="1"
                :min="1"
                :max="82800"
                controls-position="right"
                style="width:80%"
              />
              <span style="width: 50px;text-align: center; padding-left: 10px;">秒</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="放大倍数" prop="magnification">
              <el-input-number
                v-model="form.magnification"
                :precision="0"
                :min="1"
                :step="1"
                controls-position="right"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计量单位" prop="unit">
              <el-select
                v-model="form.unit"
                clearable
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="dict in dict.type.app_sensor_unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              v-if="gateway  && gateway.gatewayType && gateway.gatewayType === '1'"
              label="传感器取值地址"
              prop="outputAddress"
              :rules="gateway.gatewayType ==='1'? { required: true, message: '传感器读取地址不能为空', trigger: 'blur' } : '' "
            >
              <el-input v-model="form.outputAddress" placeholder="请输入传感器取值地址" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="gateway  && gateway.gatewayType && gateway.gatewayType === '1'"
              label="传感器设值地址"
              prop="inputAddress"
              :rules="gateway.gatewayType ==='1'? { required: true, message: '传感器设值地址不能为空', trigger: 'blur' } : '' "
            >
              <el-input v-model="form.inputAddress" placeholder="请输入传感器设值地址" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              v-if="gateway && gateway.gatewayType && gateway.gatewayType === '2'"
              label="MQTT的订阅主题"
              prop="mqttTopic"
              :rules="gateway.gatewayType ==='2'? { required: true, message: 'MQTT的订阅主题不能为空', trigger: 'blur' } : '' "
            >
              <el-input v-model="form.mqttTopic" placeholder="请输入MQTT的订阅主题" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="gateway  && gateway.gatewayType && gateway.gatewayType === '2'"
              label="MQTT的通道号"
              prop="mqttDeviceChannel"
              :rules="gateway.gatewayType ==='2'? { required: true, message: 'MQTT的MQTT的通道号不能为空', trigger: 'blur' } : '' "
            >
              <el-input v-model="form.mqttDeviceChannel" placeholder="请输入MQTT的通道号" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              v-if="gateway  && gateway.gatewayType && gateway.gatewayType === '2'"
              label="MQTT的设备名称"
              prop="mqttDeviceName"
              :rules="gateway.gatewayType ==='2'? { required: true, message: 'MQTT的设备名称不能为空', trigger: 'blur' } : '' "
            >
              <el-input v-model="form.mqttDeviceName" placeholder="请输入MQTT的设备名称" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="gateway  && gateway.gatewayType && gateway.gatewayType === '2'"
              label="MQTT的标记"
              prop="mqttDeviceTag"
              :rules="gateway.gatewayType ==='2'? { required: true, message: 'MQTT的标记不能为空', trigger: 'blur' } : '' "
            >
              <el-input v-model="form.mqttDeviceTag" placeholder="请输入MQTT的标记" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-row :span="24">
            <el-form-item
              v-if="gateway  && gateway.gatewayType && gateway.gatewayType === '2'"
              label="MQTT写入主题"
              prop="mqttWriteTopic"
              :rules="gateway.gatewayType ==='2' && isUsed === '1' ? { required: true, message: 'MQTT写入主题不能为空', trigger: 'blur' } : '' "
            >
              <el-input v-model="form.mqttWriteTopic" placeholder="请输入MQTT写入主题" clearable/>
            </el-form-item>
          </el-row>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="面板显示">
              <el-radio-group v-model="form.isDisplay">
                <el-radio
                  v-for="dict in dict.type.app_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="参与能耗计算">
              <el-radio-group v-model="form.isEnergy">
                <el-radio
                  v-for="dict in dict.type.app_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否专门用途" prop="isUsed" style="width: 100%">
              <el-radio-group v-model="isUsed" style="width: 240px">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-if="isUsed === '1'" label="用途"
                      prop="usedTypeValue">
          <!--                      :rules="isUsed === '1' ? { required: true, message: '用途不能为空', trigger: 'blur' } : '' "-->
          <el-radio-group v-model="usedTypeValue" style="width:540px">
            <el-radio
              v-for="item in usedType"
              :key="item.id"
              :label="item.value"
              style="margin: 5px"
            >{{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否启用多值管理" prop="isMultiValued" style="width: 100%">
          <el-radio-group v-model="isMultiValued" style="width: 240px" @change="multiValuedChange">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="isMultiValued === '1'" style="width: 100%">
          <el-table :data="form.sensorMultiValuedList">
            <el-table-column label="数值" align="center" prop="value">
              <template slot-scope="scope">
                <el-input v-model="scope.row.value"/>
              </template>
            </el-table-column>
            <el-table-column label="含义" align="center" prop="meaning">
              <template slot-scope="scope">
                <el-input v-model="scope.row.meaning"/>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="addMultiValued(scope.$index, scope.row)"
                  v-hasPermi="['app:sensor:edit']"
                >增加
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="delMultiValued(scope.$index, scope.row)"
                  v-hasPermi="['app:sensor:edit']"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <el-form v-show="isUpload" ref="formUpload" :model="formUpload" size="small" style="width: 850px">
        <div style="display: flex;">
          <div style="width: 350px;height: 100%">
            <el-upload
              :action="uploadFileUrl+'?sid='+this.sid"
              :before-upload="handleBeforeUpload"
              :data="deployInfo"
              :headers="headers"
              :on-error="handleUploadError"
              :on-exceed="handleExceed"
              :on-success="handleUploadSuccess"
              class="upload-demo"
              :multiple="false"
              accept=".xls,.xlsx"
              :show-file-list="false"
              :disabled="haveUploaded"
              drag
            >
              <i class="el-icon-upload"/>
              <div class="el-upload__text">
                将文件拖到此处，或
                <em>点击上传</em>
              </div>
              <div slot="tip" class="el-upload__tip">请上传传感器导入文件。
                <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                         @click="importTemplate">下载模板
                </el-link>
              </div>
            </el-upload>
          </div>
          <div style="display: flex;flex: 1;height: 100%;">
            <div class="chart-wrapper">
              <el-steps style="width: 400px" :active="processTag" finish-status="success">
                <el-step title="未上传"/>
                <el-step title="上传"/>
                <el-step title="数据准备" description="耗时约:160秒"/>
                <el-step title="验证"
                         :description="uploadFileTime.verifyTime ? '耗时约:'+uploadFileTime.verifyTime+'秒' : ''"/>
                <el-step title="导入"
                         :description="uploadFileTime.addTime ? '耗时约:'+uploadFileTime.addTime+'秒' : ''"/>
              </el-steps>
            </div>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-show="!isUpload" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 分配传感器数据权限对话框 -->
    <el-dialog :title="title" :visible.sync="openDeptScope" width="500px" append-to-body>
      <el-form :model="form" label-width="80px">
        <el-form-item label="传感器名称">
          <el-input v-model="form.sensorName" :disabled="true"/>
        </el-form-item>
        <el-form-item label="部门权限">
          <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠</el-checkbox>
          <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选
          </el-checkbox>
          <el-tree
            class="tree-border"
            :data="deptOptions"
            show-checkbox
            default-expand-all
            ref="dept"
            node-key="id"
            :check-strictly="true"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDeptScope">确 定</el-button>
        <el-button @click="cancelDeptScope">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 分配传感器空间权限对话框 -->
    <el-dialog :title="title" :visible.sync="openPlaceScope" width="500px" append-to-body>
      <el-form :model="form" label-width="80px">
        <el-form-item label="传感器名称">
          <el-input v-model="form.sensorName" :disabled="true"/>
        </el-form-item>
        <el-form-item label="空间权限">
          <el-checkbox v-model="placeExpand" @change="handleCheckedTreeExpand($event, 'place')">展开/折叠</el-checkbox>
          <el-checkbox v-model="placeNodeAll" @change="handleCheckedTreeNodeAll($event, 'place')">全选/全不选
          </el-checkbox>
          <el-tree
            class="tree-border"
            :data="placeOptions"
            show-checkbox
            default-expand-all
            ref="place"
            node-key="id"
            :check-strictly="true"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPlaceScope">确 定</el-button>
        <el-button @click="cancelPlaceScope">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看数值记录 -->
    <el-dialog :title="title" :visible.sync="recordOpen" width="80%" append-to-body :close-on-click-modal="false">

      <div slot="footer" class="dialog-footer">
        <el-table v-loading="recordLoading" :data="sensorRecordList">
          <el-table-column label="传感器" align="center" prop="sensorId">
            <template slot-scope="scope">
              <span>{{ scope.row.appSensor ? scope.row.appSensor.sensorName : '' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="传感器值" align="center" prop="value"/>
          <el-table-column prop="updateTime" label="更新时间"/>
        </el-table>
        <pagination
          v-show="recordTotal>0"
          :total="recordTotal"
          :page.sync="queryParamsRecord.pageNum"
          :limit.sync="queryParamsRecord.pageSize"
          @pagination="getRecordList"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addSensor,
  delSensor,
  delSensorAll,
  deptScope,
  deptTreeSelect,
  getSensor,
  listSensor,
  placeScope,
  placeTreeSelect,
  updateSensor
} from "@/api/app/sensor";
import {listSimple} from "@/api/app/device";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getToken} from "@/utils/auth";
import {listRule} from "@/api/app/rule";

import {listSensorRecord} from "@/api/app/sensorRecord";
import {listAllProject} from "@/api/app/project";

export default {
  name: "Sensor",
  dicts: ['app_yes_no', 'app_sensor_type', 'app_sensor_unit'],
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      recordLoading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      newAdd: false,
      // 总条数
      total: 0,
      // 总条数
      recordTotal: 0,
      // 传感器管理表格数据
      sensorList: [],
      sensorRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      recordOpen: false,
      // 是否上传
      isUpload: false,
      deployInfo: {},
      // 是否显示弹出层（数据权限）
      openDeptScope: false,
      // 是否显示弹出层（数据权限）
      openPlaceScope: false,
      // 重新渲染表格状态
      refreshTable: true,
      deptExpand: true,
      deptNodeAll: false,
      placeExpand: true,
      placeNodeAll: false,
      // 部门列表
      deptOptions: [],
      // 空间列表
      placeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceId: null,
        projectId: null,
        mqttTopic: null,
        sensorCode: null,
        sensorName: null,
        sensorType: null,
        unit: null,
      },
      // 查询参数
      queryParamsRecord: {
        pageNum: 1,
        pageSize: 10,
        sensorId: null,
      },
      processTag: 0,
      // 表单参数
      form: {},
      formUpload: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        gateway: [
          {required: true, message: "网关不能为空", trigger: "blur"}
        ],
        deviceId: [
          {required: true, message: "所属设备不能为空", trigger: "blur"}
        ],
        faultRuleId: [
          {required: true, message: '设备告警类型不能为空', trigger: 'blur'}
        ],
        sensorType: [
          {required: true, message: "传感器类型不能为空", trigger: "blur"}
        ],
        sensorCode: [
          {required: true, message: '传感器编号不能为空', trigger: 'blur'}
        ],
        sensorName: [
          {required: true, message: '传感器名字不能为空', trigger: 'blur'}
        ],
        unit: [
          {required: true, message: '计量单位不能为空', trigger: 'blur'}
        ],
      },
      usedType: [{id: 1, value: 1, label: '灯光控制'},
        {id: 2, value: 2, label: '强制排风'},
        {id: 3, value: 3, label: '窗高控制'},
        {id: 4, value: 4, label: '电源开关'},
        {id: 5, value: 5, label: '有无人'},
        {id: 6, value: 6, label: '静音控制'},
        {id: 7, value: 7, label: '排风阀'},
        {id: 8, value: 8, label: '新风阀'},
        {id: 9, value: 9, label: '自动门'},
        {id: 10, value: 10, label: '工作模式'}
      ],
      usedTypeValue: null,
      deviceList: [],
      gatewayList: [],
      faultRuleList: [],
      projectOptions: [],
      isUsed: '0',
      isMultiValued: '0',
      gateway: {
        gatewayType: '0'
      },
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/app/sensor/upload", // 上传的文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileType: ["xls", "xlsx"],
      fileSize: 5,
      uploadFileTime: {},
      haveUploaded: false,
      sid: null,
      timer: null,
      source: null,
    };
  },
  mounted() {
  },
  created() {
    this.getList();
    this.getProject();
    this.getDevices();
    this.getFaultRules();
    this.sid = new Date().getTime();
    // this.initWebSocket();
    this.initSSE();
  },
  destroyed() {
    if (this.timer) {
      // clearInterval(this.timer)
    }
    this.websock.close();
    // this.closeSSE();
  },
  methods: {
    /** 查询传感器管理列表 */
    getList() {
      this.loading = true;
      listSensor(this.queryParams).then(response => {
        this.sensorList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询传感器管理列表 */
    getRecordList() {
      this.recordLoading = true;
      listSensorRecord(this.queryParamsRecord).then(response => {
        this.sensorRecordList = response.rows;
        this.recordTotal = response.total;
        this.recordLoading = false;
      });
    },
    getDevices(e) {
      console.log("开始请求设备:" + Date.now())
      let query = {
        pageNum: 1,
        pageSize: 100000
      };
      if (e) {
        query.projectId = e;
      }
      listSimple(query).then(response => {
        console.log("请求结束设备:" + Date.now())
        this.deviceList = this.handleTree(response.data, "deviceId");
        console.log("处理结束:" + Date.now())
      })
    },
    getProject() {
      listAllProject().then(response => {
        this.projectOptions = response.data
      })
    },
    getFaultRules() {
      listRule({
        pageNum: 1,
        pageSize: 100000
      }).then(res => {
        this.faultRuleList = res.rows
      })
    },
    /** 转换设备数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deviceId,
        label: node.deviceName,
        children: node.children
      };
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys();
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 所有空间位置节点数据
    getPlaceAllCheckedKeys() {
      // 目前被选中的空间位置节点
      let checkedKeys = this.$refs.place.getCheckedKeys();
      // 半选中的空间位置节点
      let halfCheckedKeys = this.$refs.place.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    /** 根据角色ID查询部门树结构 */
    getDeptTree(sensorId) {
      return deptTreeSelect(sensorId).then(response => {
        this.deptOptions = response.depts;
        return response;
      });
    },
    /** 根据角色ID查询空间位置树结构 */
    getPlaceTree(sensorId) {
      return placeTreeSelect(sensorId).then(response => {
        this.placeOptions = response.places;
        return response;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 关闭按钮
    recordClose() {
      this.recordOpen = false;
    },
    // 表单重置
    reset() {
      this.form = {
        deviceId: null,
        mqttTopic: null,
        mqttDeviceChannel: null,
        mqttDeviceName: null,
        mqttDeviceTag: null,
        mqttWriteTopic: null,
        faultRuleId: null,
        sensorCode: null,
        sensorName: null,
        sensorType: null,
        outputAddress: null,
        inputAddress: null,
        value: null,
        intervalTime: null,
        magnification: null,
        unit: null,
        isDisplay: null,
        isEnergy: null,
        isLight: null,
        isExhaust: null,
        isHeight: null,
        isOn: null,
        isMute: null,
        isForce: null,
        isFresh: null,
        isBeing: null,
        isAutoDoor: null,
        workMode: null,
        tdCode: null,
        gateway: null,
        sensorMultiValuedList: []
      };
      this.isUsed = "0"
      this.usedTypeValue = null
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sensorId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isUpload = false;
      this.title = "添加传感器管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isUpload = false;
      const sensorId = row.sensorId || this.ids
      getSensor(sensorId).then(response => {
        this.form = response.data;
        if (this.form.isLight === '1') {
          this.isUsed = '1'
          this.usedTypeValue = 1
        } else if (this.form.isForce === '1') {
          this.isUsed = '1'
          this.usedTypeValue = 2
        } else if (this.form.isHeight === '1') {
          this.isUsed = '1'
          this.usedTypeValue = 3
        } else if (this.form.isOn === '1') {
          this.isUsed = '1'
          this.usedTypeValue = 4
        } else if (this.form.isBeing === '1') {
          this.isUsed = '1'
          this.usedTypeValue = 5
        } else if (this.form.isMute === '1') {
          this.isUsed = '1'
          this.usedTypeValue = 6
        } else if (this.form.isExhaust === '1') {
          this.isUsed = '1'
          this.usedTypeValue = 7
        } else if (this.form.isFresh === '1') {
          this.isUsed = '1'
          this.usedTypeValue = 8
        } else if (this.form.isAutoDoor === '1') {
          this.isUsed = '1'
          this.usedTypeValue = 9
        } else if (this.form.workMode === '1') {
          this.isUsed = '1'
          this.usedTypeValue = 10
        }
        this.form.isDisplay = this.form.isDisplay + ''
        this.form.isEnergy = this.form.isEnergy + ''
        if (!this.form.sensorMultiValuedList) {
          this.form.sensorMultiValuedList = []
        } else if (this.form.sensorMultiValuedList.length > 0) {
          this.isMultiValued = "1"
        }
        this.gateway = response.data.device.appGateway
        this.open = true;
        this.title = "修改传感器管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.device && this.form.device.appGateway && this.form.device.appGateway.gatewayType === '1'
            && (!this.judgeNumber(this.form.outputAddress) || (Number(this.form.outputAddress) / 10000) < 1)) {
            this.$message({
              message: '读取地址必须是正确的寄存器地址',
              type: 'warning'
            })
            return false
          }
          this.form.isLight = '0'
          this.form.isExhaust = '0'
          this.form.isHeight = '0'
          this.form.isOn = '0'
          this.form.isBeing = '0'
          this.form.isMute = '0'
          this.form.isForce = '0'
          this.form.isFresh = '0'
          this.form.isAutoDoor = '0'
          this.form.workMode = '0'
          if (this.usedTypeValue != null && this.isUsed === '1') {
            switch (this.usedTypeValue) {
              case 1:
                this.form.isLight = '1'
                break
              case 2:
                this.form.isForce = '1'
                break
              case 3:
                this.form.isHeight = '1'
                break
              case 4:
                this.form.isOn = '1'
                break
              case 5:
                this.form.isBeing = '1'
                break
              case 6:
                this.form.isMute = '1'
                break
              case 7:
                this.form.isExhaust = '1'
                break
              case 8:
                this.form.isFresh = '1'
                break
              case 9:
                this.form.isAutoDoor = '1'
                break
              case 10:
                this.form.workMode = '1'
                break
            }
          }
          if (this.form.isLight === '1' ||
            this.form.isForce === '1' ||
            this.form.isHeight === '1' ||
            this.form.isOn === '1' ||
            this.form.isBeing === '1' ||
            this.form.isMute === '1' ||
            this.form.isExhaust === '1' ||
            this.form.isFresh === '1' ||
            this.form.isAutoDoor === '1' ||
            this.form.workMode === '1'
          ) {
            if (this.form.device && this.form.device.appGateway && this.form.device.appGateway.gatewayType === '1' && this.form.inputAddress == null) {
              this.$message({
                message: '当需要有控制的要求时，设值地址不能为空',
                type: 'warning'
              })
              return false
            } else if (this.form.device && this.form.device.appGateway && this.form.device.appGateway.gatewayType === '1'
              && this.form.inputAddress !== null && this.form.inputAddress.trim() !== '' &&
              this.judgeNumber(this.form.inputAddress) &&
              (Number(this.form.inputAddress) / 10000) < 1) {
              this.$message({
                message: '设值地址必须是正确的寄存器地址',
                type: 'warning'
              })
              return false
            }
          }
          if (this.form.sensorId != null) {
            updateSensor(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSensor(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const sensorIds = row.sensorId || this.ids;
      this.$modal.confirm('是否确认删除传感器管理编号为"' + sensorIds + '"的数据项？').then(function () {
        return delSensor(sensorIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 删除按钮操作 */
    handleDeleteAll() {
      this.$modal.confirm('是否确认删除所有传感器管理？').then(function () {
        return delSensorAll();
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('app/sensor/export', {
        ...this.queryParams
      }, `sensor_${new Date().getTime()}.xlsx`)
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('app/sensor/importTemplate', {}, `传感器导入模版_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleUpload() {
      this.isUpload = true;
      this.open = true;
      this.processTag = 0
      this.uploadFileTime = {};
    },
    judgeNumber(str) {
      const numReg = /^[0-9]+$/
      const numRe = new RegExp(numReg)
      return numRe.test(str)
    },
    deviceSelect(node, instanceId) {
      this.gateway = node.appGateway
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      this.$modal.closeLoading();
      if (res.code === 200) {
        this.processTag = 2;
        this.uploadFileTime = res.data;
        this.$modal.msgSuccess("文件上传成功,进入数据处理");
      } else {
        this.$modal.msgError(res.msg);
        this.processTag = 0;
        this.uploadFileTime = {};
      }
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = function () {
          this.fileType.forEach((type) => {
            if (file.type.indexOf(type) > -1) return true;
            if (fileExtension && fileExtension.indexOf(type) > -1) return true;
            return false;
          })
        };
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传文件，请稍候...");
      this.processTag = 1;
      this.uploadFileTime = {};
      this.haveUploaded = true;
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
      this.haveUploaded = false;
    },
    // 监听上传失败
    handleUploadError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.haveUploaded = false;
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
    },
    initSSE() {
      if (window.EventSource) {
         this.source = new EventSource("http://59.110.170.159:8080/sse/createConnect?clientId=" + this.sid)
        this.source.addEventListener('open', function (e) {
          console.log("建立连接", e)
        })
        /**
         * 客户端收到服务器发来的数据
         * 另一种写法：source.onmessage = function (event) {}
         */
        let _this = this;
        this.source.addEventListener('message', function (e) {
          console.log(e.data);
          if (e.data) {
            let  data = JSON.parse(e.data);
            if (data.data) {
              data = JSON.parse(data.data)
              if (data.msgType === 2) {
                if (data.msg === '服务器收到文件') {
                  _this.processTag = 2
                } else if (data.msg === '数据准备完成') {
                  _this.processTag = 3
                } else if (data.msg === '验证通过，正在进行导入...') {
                  _this.processTag = 4
                } else if (data.msg === '导入成功') {
                  _this.processTag = 3
                  _this.getList()
                  _this.isUpload = false;
                  _this.open = false;
                  _this.haveUploaded = false;
                  console.log('导入成功')
                }
                _this.$notify({
                  title: '',
                  message: data.msg,
                  type: 'success',
                  dangerouslyUseHTMLString: true,
                  duration: 2000
                })
              } else if (data.msgType === 3) {
                _this.processTag = 0
                _this.haveUploaded = false;
                _this.uploadFileTime = {};
                _this.$notify({
                  title: '',
                  message: data.msg,
                  dangerouslyUseHTMLString: true,
                  type: 'error',
                  duration: 10000
                })
              }
            }
          }
        });


        /**
         * 如果发生通信错误（比如连接中断），就会触发error事件
         * 或者：
         * 另一种写法：source.onerror = function (event) {}
         */
        this.source.addEventListener('error', function (e) {
          this.source.close();
          if (e.readyState === EventSource.CLOSED) {
            console.log("连接关闭");
          } else {
            console.log(e);
          }
        }, false);
      }
    },
    closeSSE(){
      if (this.source) {
        new EventSource(process.env.VUE_APP_BASE_API + "/sse/closeConnect?clientId=" + this.sid)
        this.source.close();
      }
    },
    initWebSocket() {
      console.log(process)
      const wsUri = process.env.VUE_APP_WS_API + '/webSocket/' + this.sid;
      this.websock = new WebSocket(wsUri)
      this.websock.onerror = this.webSocketOnError
      this.websock.onmessage = this.webSocketOnMessage
      this.websock.onopen = function (event) {
        console.log('WebSocket 连接已打开')
      }
      this.timer = setInterval(() => {
        const data = {type: 'HEARTBEAT'};
        if (this.websock.readyState === WebSocket.OPEN) {
          this.websock.send(JSON.stringify(data))
        }
      }, 10000)
    },
    webSocketOnError(e) {
      console.log('WebSocket连接发生错误', e);
      this.$notify({
        title: 'WebSocket连接发生错误',
        type: 'error',
        duration: 2000
      })
    },
    webSocketOnMessage(e) {
      const data = JSON.parse(e.data)
      if (data.msgType === 'INFO') {
        if (data.msg === '服务器收到文件') {
          this.processTag = 2
        } else if (data.msg === '数据准备完成') {
          this.processTag = 3
        } else if (data.msg === '验证通过，正在进行导入...') {
          this.processTag = 4
        } else if (data.msg === '导入成功') {
          this.processTag = 3
          this.getList()
          this.isUpload = false;
          this.open = false;
          this.haveUploaded = false;
          console.log('导入成功')
        }
        this.$notify({
          title: '',
          message: data.msg,
          type: 'success',
          dangerouslyUseHTMLString: true,
          duration: 10000
        })
      } else if (data.msgType === 'ERROR') {
        this.processTag = 0
        this.haveUploaded = false;
        this.uploadFileTime = {};
        this.$notify({
          title: '',
          message: data.msg,
          dangerouslyUseHTMLString: true,
          type: 'error',
          duration: 0
        })
      }
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type === 'dept') {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type === 'place') {
        let treeList = this.placeOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.place.store.nodesMap[treeList[i].id].expanded = value;
        }

      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type === 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
      } else if (type === 'place') {
        this.$refs.place.setCheckedNodes(value ? this.placeOptions : []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type === 'dept') {
        this.form.deptCheckStrictly = !!value;
      } else if (type === 'place') {
        this.form.placeCheckStrictly = !!value;
      }
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handlePlaceScope":
          this.handlePlaceScope(row);
          break;
        case "handleDeptScope":
          this.handleDeptScope(row);
          break;
        case "handleOpenRecord":
          this.handleOpenRecord(row);
          break;
        default:
          break;
      }
    },
    /** 分配部门权限操作 */
    handleDeptScope(row) {
      this.reset();
      const deptTreeSelect = this.getDeptTree(row.sensorId);
      getSensor(row.sensorId).then(response => {
        this.form = response.data;
        this.openDeptScope = true;
        this.$nextTick(() => {
          deptTreeSelect.then(res => {
            this.$refs.dept.setCheckedKeys(res.checkedKeys);
          });
        });
        this.title = "分配部门权限";
      });
    },
    /** 分配空间权限操作 */
    handlePlaceScope(row) {
      this.reset();
      const placeTreeSelect = this.getPlaceTree(row.sensorId);
      getSensor(row.sensorId).then(response => {
        this.form = response.data;
        this.openPlaceScope = true;
        this.$nextTick(() => {
          placeTreeSelect.then(res => {
            this.$refs.place.setCheckedKeys(res.checkedKeys);
          });
        });
        this.title = "分配空间权限";
      });
    },

    handleOpenRecord(row) {
      this.title = row.sensorName + "数据更新记录"
      this.recordOpen = true;
      this.queryParamsRecord.sensorId = row.sensorId;
      this.getRecordList();
    },

    /** 提交按钮（数据权限） */
    submitDeptScope: function () {
      if (this.form.sensorId !== null && (typeof this.form.sensorId) !== 'undefined') {
        this.form.deptIds = this.getDeptAllCheckedKeys();
        deptScope(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.openDeptScope = false;
          this.getList();
          if (this.newAdd === true) {
            this.handlePlaceScope(this.form)
            this.newAdd = false;
          }
        });
      }
    },
    /** 提交按钮（数据权限） */
    submitPlaceScope: function () {
      if (this.form.sensorId !== null && (typeof this.form.sensorId) !== 'undefined') {
        this.form.placeIds = this.getPlaceAllCheckedKeys();
        placeScope(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.openPlaceScope = false;
          this.getList();
        });
      }
    },
    // 取消按钮（数据权限）
    cancelDeptScope() {
      this.openDeptScope = false;
      this.reset();
      if (this.newAdd === true) {
        this.handlePlaceScope(this.newData)
        this.newAdd = false;
      }
    },
    // 取消按钮（空间权限）
    cancelPlaceScope() {
      this.openPlaceScope = false;
      this.reset();
    },
    multiValuedChange(e) {
      if (e === '1') {
        if (!this.form.sensorMultiValuedList) {
          this.form.sensorMultiValuedList = []
          this.form.sensorMultiValuedList.push({
            value: null,
            meaning: null
          })
        } else if (this.form.sensorMultiValuedList.length === 0) {
          this.form.sensorMultiValuedList.push({
            value: null,
            meaning: null
          })
        }
      } else {
        this.form.sensorMultiValuedList = []
      }
    },
    addMultiValued(index, row) {
      this.form.sensorMultiValuedList.splice(index + 1, 0, {
        value: null,
        meaning: null
      })
    },
    delMultiValued(index, row) {
      this.form.sensorMultiValuedList.splice(index, 1)
    },
    projectChange(e) {
      this.getDevices(e)
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
::v-deep .vue-treeselect__control, ::v-deep .vue-treeselect__placeholder, ::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}

.chart-wrapper {
  background: #fff;
  padding: 80px 40px 0;
  margin: 0 auto;
}

.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.is-process .el-step__icon-inner {
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
